package middlewarex

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
)

// RequestId gin框架追踪ID中间件
// 建议放在中间件组里第一个
// 传递之前就存在的requestId或生成新的requestId
func RequestId() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 检查之前是否有request id有则沿用
		requestID := c.Request.Header.Get("X-Request-Id")
		if requestID == "" {
			// 没有request-id生成一个新的
			requestID = helperx.MakeRequestId()
			// 将request-id写回header中
			c.Writer.Header().Set("X-Request-Id", requestID)
		}

		// 设置request-id在本context里
		c.Set("RequestId", requestID)

		// 将日志对象放入context中，同时带上request-id和client-ip
		c.Set("zap_trace", logx.Zap().With(
			zap.String("request_id", requestID),
		))

		c.Next()
	}
}
